package sample.controller.category;

import java.util.Date;
import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.StringUtil;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Transaction;

public class AddController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger = Logger.getLogger(AddController.class.getName());

    @Override
    public Navigation run() {

        String name = asString("name");
        if (!StringUtil.isEmpty(name)) {
            DatastoreService datastoreService = DatastoreServiceFactory
                    .getDatastoreService();
            
            // 保存
            Entity todo = new Entity("Category");
            todo.setProperty("name", asString("name"));
            todo.setProperty("createdAt", new Date());
    
            Transaction transaction = datastoreService.beginTransaction();
            try {
                datastoreService.put(transaction, todo);
                transaction.commit();
            } finally {
                if (transaction.isActive()) {
                    transaction.rollback();
                }
            }
        }
        return forward("add.jsp");
    }
}
